package com.baibei.ebec.user.register;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baibei.basic.module.utils.ViewExtCompat;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.ebec.user.R;
import com.baibei.ebec.user.R2;
import com.baibei.model.event.LoginEvent;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicFragment;
import com.baibei.ui.AppUI;
import com.blankj.utilcode.utils.LogUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

/**
 * 注册：个人用户、企业用户
 * Created by ChenRui on 2017/8/2 0002 15:52.
 */
public class RegisterFragment extends BasicFragment implements RegisterContract.View {


    private int mType;
    private TextWatcher mTextWatcher;


    public static RegisterFragment newInstance(int type) {
        Bundle args = new Bundle();
        args.putInt("type", type);
        RegisterFragment fragment = new RegisterFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fm_register_personal;
    }

    @BindView(R2.id.et_phone)
    EditText mPhoneText;

    @BindView(R2.id.et_password)
    EditText mPasswordText;
    @BindView(R2.id.et_org_no)
    EditText mOrgNoText;

    @BindView(R2.id.et_sms_code)
    EditText mSmsCodeText;

    @BindView(R2.id.btn_register)
    Button mRegisterButton;

    @BindView(R2.id.img_edit_delete)
    ImageView mEditDeleteView;

    @BindView(R2.id.cb_eyes)
    CheckBox mEyes;

    @BindView(R2.id.btn_send_sms)
    TextView mSendSMSView;

    @BindView(R2.id.tv_user_contract_tips)
    TextView mContractView;

    @BindView(R2.id.layout_invitedcode)
    View mLayoutInvitedCode;

    private RegisterContract.Presenter mPresenter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = inject(RegisterContract.Presenter.class);
        mType = getArguments().getInt("type", IUserApi.TYPE_PERSONAL);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ViewExtCompat.relevancePasswordVisibility(mEyes, mPasswordText);
        // 企业用户
        if (mType == IUserApi.TYPE_ENTERPRISE) {
            mRegisterButton.setText(R.string.next_step);
            mContractView.setText(R.string.contract_enterprise_tips);
//            mOrgNoText.setVisibility(View.GONE);
            ((View) mOrgNoText.getParent()).setVisibility(View.GONE);
        }


        mTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mPhoneText.length() >= 11 && mPasswordText.length() >= 6 && mSmsCodeText.length() >= 4) {
//                    boolean enable = true;
//                    if (mType == IUserApi.TYPE_PERSONAL) {
//                        enable = mOrgNoText.length() > 0;
//                    }
                    mRegisterButton.setEnabled(true);
                } else {
                    mRegisterButton.setEnabled(false);
                }
                mEditDeleteView.setVisibility(mPhoneText.length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };

        TextViewCompat.registerFormListener(mTextWatcher, mPhoneText, mPasswordText, mSmsCodeText, mOrgNoText);

        //是否开启注册邀请码
        //Todo 注册
//        if (com.baibei.ebec.user.BuildConfig.ISSHOWINVITEDCODE) {
//            mLayoutInvitedCode.setVisibility(View.VISIBLE);
//        } else {
//            mLayoutInvitedCode.setVisibility(View.GONE);
//        }

    }


    @Override
    public void onDestroyView() {
        TextViewCompat.unregisterFormListener(mTextWatcher, mPhoneText, mPasswordText, mSmsCodeText, mOrgNoText);
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        mPresenter.destroy();
        super.onDestroy();
    }

    private void showLoading() {
        mRegisterButton.setEnabled(false);
        mPhoneText.setEnabled(false);
        mPasswordText.setEnabled(false);
        AppUI.loading(getContext(), getString(R.string.register_loading)).setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dismissLoading();
                mPresenter.cancel();
            }
        });
    }

    private void dismissLoading() {
        if (mRegisterButton == null) return;
        mRegisterButton.setEnabled(!TextUtils.isEmpty(getPassword()));
        mPhoneText.setEnabled(true);
        mPasswordText.setEnabled(true);
        AppUI.dismiss();
    }

    @OnClick(R2.id.btn_register)
    public void onRegClick() {
        showLoading();
        mPresenter.register();
    }

    @Override
    public String getMobile() {
        return mPhoneText.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return mPasswordText.getText().toString().trim();
    }

    @Override
    public String getSmsCode() {
        return mSmsCodeText.getText().toString();
    }

    @Override
    public String getInvitationCode() {
        //如果不开启输入邀请码，使用填写
        if (com.baibei.ebec.user.BuildConfig.ISSHOWINVITEDCODE) {
            return mOrgNoText.getText().toString();
        }
        return com.baibei.ebec.user.BuildConfig.INVITEDCODE;
    }

    @Override
    public String getImei() {
        TelephonyManager tm = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            String imei = tm.getDeviceId();

            return imei;
        } else {

            return null;
        }
    }

    @Override
    public String getInviteCode() {
        return mOrgNoText.getText().toString();
    }


    @Override
    public void onRegisterSuccess() {
        EventBus.getDefault().post(new LoginEvent(true,true));
        dismissLoading();
        // 企业用户跳到下一步
        if (mType == IUserApi.TYPE_ENTERPRISE) {
            AppRouter.routeToRegisterEnterprise(getActivity(), getMobile(), getSmsCode(), getPassword());
        } else {
            AppUI.success(getContext(), "注册成功！");
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
        }
    }

    @Override
    public void onRegisterFailed(String msg) {
        dismissLoading();
        AppUI.success(getContext(), msg);
    }

    @Override
    public int getType() {
        return mType;
    }

    @OnClick(R2.id.img_edit_delete)
    public void onEditDeleteClick() {
        mPhoneText.setText("");
    }

    @OnClick(R2.id.btn_send_sms)
    public void onSendSmsClick() {
        mSendSMSView.setEnabled(false);
        mPresenter.sendSMS();
    }

    @Override
    public void onSmsSuccess() {
        AppUI.success(getContext(), getString(R.string.send_sms_success));
    }

    @Override
    public void onSmsFailed(String msg) {
        mSendSMSView.setEnabled(true);
        AppUI.failed(getContext(), msg);
    }

    @Override
    public void onSmsCountDown(int time, String text) {
        mSendSMSView.setText(text);
    }

    @Override
    public void onSmsCountDownFinish() {
        mSendSMSView.setEnabled(true);
        mSendSMSView.setText(R.string.send_sms);
    }


    @OnClick(R2.id.tv_contract)
    public void onContractClick() {
        AppRouter.routeToWeb(getContext(), "", BuildConfig.API_BASE_URL + "/cbclient/lhProtocol.html");
    }

    @OnClick(R2.id.btn_scan)
    public void onScanClick() {
        RxPermissions rxPermissions = new RxPermissions(this.getActivity());
        rxPermissions.request(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean granted) throws Exception {
                        if (granted) {
                            ZXingLibrary.initDisplayOpinion(getContext().getApplicationContext());
                            Intent intent = new Intent(getContext(), CaptureActivity.class);
                            startActivityForResult(intent, AppRouter.REQ_SCAN_CODE);
                        } else {
                            AppUI.failed(getContext(), "相机授权失败");
                        }
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppRouter.REQ_SCAN_CODE && data != null && data.getExtras() != null) {
            Bundle bundle = data.getExtras();
            if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                String result = bundle.getString(CodeUtils.RESULT_STRING);
                LogUtils.i("扫描结果:" + result);
                if (!TextUtils.isEmpty(result)) {
                    //Todo 注册
//                    Uri uri = Uri.parse(result);
//                    String value = uri.getQueryParameter("invitationCode");
//                    Log.i("扫描结果v",value);
//                    if (!TextUtils.isEmpty(value)) {
//                        mOrgNoText.setText(value);
//                    }
                    mOrgNoText.setText(result);
                    return;
                }
            } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                AppUI.success(getContext(), "解析二维码失败");
            }
        }
    }
}
